<?php
class omeanalysts_mdl_ome_deliveryexpressfeeAgent extends dbeav_model{

    //var $has_export_cnf = true;

    var $export_name = '代收代付快递费结算明细表';

    public function table_name($real=false){
        $table_name = 'ome_delivery';
        if($real){
            return kernel::database()->prefix.$table_name;
        }else{
            return $table_name;
        }
    }

    public function count($filter=null){

        $where = $this->_filter($filter); 

        $sql = "SELECT count(*) as _count from  sdb_wms_deliverycomp a 
                         inner join sdb_wms_deliverycomp_line b on a.id = b.deliverycomp_id
                         inner join sdb_wms_deliverynote_line d on b.deliverynote_id = d.deliverynote_id
                         inner join sdb_wms_delivery e on d.delivery_bn = e.delivery_bn
                         inner join sdb_wms_delivery_bill db on e.delivery_id = db.delivery_id 
                         inner join sdb_wms_delivery_items items on e.delivery_id=items.delivery_id
                         inner join sdb_ome_shop f on e.shop_id = f.shop_id
                         inner JOIN sdb_ome_delivery od on ( e.outer_delivery_bn = od.delivery_bn )
                         inner JOIN sdb_ome_delivery_order odo on ( od.delivery_id = odo.delivery_id )
                         inner JOIN sdb_ome_orders os on (odo.order_id = os.order_id)
                         inner JOIN sdb_ome_branch sob on (sob.branch_id = e.branch_id)
                         inner JOIN sdb_material_basic_material_ext ext on items.product_id=ext.bm_id
                     where  ".$where." ";
        $row = $this->db->select($sql);
        return intval($row[0]['_count']);
    }

    public function getlist($cols='*', $filter=array(), $offset=0, $limit=-1, $orderType=null){
  

        if(!$filter['time_from'] && !$filter['time_to'])
        {
            return false;
        }else{
//case when f.jstype ='0' then e.lmfee when f.jstype='1' then 0 when f.jstype='2' then 0 else e.lmfee end lmfee,
            $where = $this->_filter($filter); 
            $sql = "SELECT f.`name`,f.AXCustomer,f.customername,case when f.jstype ='0' then '代收代付' when f.jstype='1' then '理文支付' when f.jstype='2' then '客户支付' else '' end  jstype,e.logi_name,a.deliverycomp_time,e.delivery_time as delivery_time,sob.`name` as branch,d.axorderno order_bn,db.logi_no,e.ship_area,items.bn,items.product_name,items.number,ext.unit,e.net_weight/1000 net_weight,e.net_weight/1000 order_weight,
            case when f.jstype ='0' then e.delivery_cost_actual when f.jstype='1' then e.delivery_cost_actual when f.jstype='2' then 0 else e.delivery_cost_actual end  flatFeePrice,e.lmfee lmfee,
            ((case when f.jstype ='0' then e.lmfee when f.jstype='1' then 0 when f.jstype='2' then 0 else e.lmfee end) -(case when f.jstype ='0' then e.delivery_cost_actual when f.jstype='1' then e.delivery_cost_actual when f.jstype='2' then 0 else e.delivery_cost_actual end)) otherfee

                         from    sdb_wms_deliverycomp a 
                         inner join sdb_wms_deliverycomp_line b on a.id = b.deliverycomp_id
                         inner join sdb_wms_deliverynote_line d on b.deliverynote_id = d.deliverynote_id
                         inner join sdb_wms_delivery e on d.delivery_bn = e.delivery_bn
                         inner join sdb_wms_delivery_bill db on e.delivery_id = db.delivery_id 
                         inner join sdb_wms_delivery_items items on e.delivery_id=items.delivery_id
                         inner join sdb_ome_shop f on e.shop_id = f.shop_id
                         inner JOIN sdb_ome_delivery od on ( e.outer_delivery_bn = od.delivery_bn )
                         inner JOIN sdb_ome_delivery_order odo on ( od.delivery_id = odo.delivery_id )
                         inner JOIN sdb_ome_orders os on (odo.order_id = os.order_id)
                         inner JOIN sdb_ome_branch sob on (sob.branch_id = e.branch_id)
                         inner JOIN sdb_material_basic_material_ext ext on items.product_id=ext.bm_id 
                     where  ".$where." "; 
            $rows = $this->db->selectLimit($sql,$limit,$offset);
            
            return $rows;
        }
        
    }
    
    public function searchOptions(){
        $parentOptions = parent::searchOptions();
        $childOptions = array(
            'order_bn'=>app::get('base')->_('订单号'),
        );
        return $Options = array_merge($parentOptions,$childOptions);
    }

    public function _filter($filter,$tableAlias=null,$baseWhere=null){


        $where = array(1);
       if(empty($filter['time_from']))
        {
          $where[]=' 1=2 ';
        }
        if(isset($filter['time_from']) && $filter['time_from']){
            $where[] = ' a.deliverycomp_time >='.strtotime($filter['time_from']);
        }
        if(isset($filter['time_to']) && $filter['time_to']){
            $where[] = ' a.deliverycomp_time <'.(strtotime($filter['time_to'])+86399);
        }
        if(isset($filter['shop_id'])   && $filter['shop_id']){
            $where[] = ' f.shop_id  =\''.addslashes($filter['shop_id']).'\'';
        }
        if(!$filter['shop_id'] && $filter['shop_ids']){
            $where[] = ' f.shop_id IN (\''.implode('\',\'', $filter['shop_ids']).'\')';
        }
        unset($filter['shop_id']);
        if(isset($filter['AXCustomer']) && $filter['AXCustomer']){
            $where[]= ' f.AXCustomer  =\''.addslashes($filter['AXCustomer']).'\'';
        }

        if(isset($filter['branch_id'])   && $filter['branch_id']){
            $where[] = ' sob.branch_id  =\''.addslashes($filter['branch_id']).'\'';
        }
        if(!$filter['branch_id'] && $filter['branch_ids']){
            $where[] = ' sob.branch_id IN (\''.implode('\',\'', $filter['branch_ids']).'\')';
        }
        
        unset($filter['branch_id']);

        if(isset($filter['p_bn']) && $filter['p_bn']){
            $where[] = ' items.bn =\''.addslashes($filter['p_bn']).'\'';
        }
        if(isset($filter['logi_no']) && $filter['logi_no']){
            $where[] = ' db.logi_no =\''.addslashes($filter['logi_no']).'\'';
        }
        if(isset($filter['dlycorp']) && $filter['dlycorp']){
            $where[] = ' e.logi_id  =\''.addslashes($filter['dlycorp']).'\'';
        }


        return implode($where,' AND ');
    }

    public function get_schema(){
        $schema = array (
            'columns' => array (
                'name' =>
                array (
                  'type' => 'varchar(255)',
                  'required' => true,
                  'label' => '店铺',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '120',
                ),
                'AXCustomer' =>
                array (
                  'type' => 'varchar(255)',
                  'required' => true,
                  'label' => '客户编码',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '120',
                ),
                'customername' =>
                array (
                  'type' => 'varchar(255)',
                  'required' => true,
                  'label' => '客户名称',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '120',
                ),
                'jstype' =>
                array (
                  'type' => 'varchar(15)',
                  'label' => '结算方式',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '70',
                ),
                'order_bn' =>
                array(
                    'type' => 'varchar(32)',
                    'required' => true,
                    'label' => 'AX订单号',
                    'is_title' => true,
                    'width' => 125,
                    'searchtype' => 'nequal',
                    'editable' => false,
                    'filtertype' => 'normal',
                    'filterdefault' => true,
                    'in_list' => true,
                    'default_in_list' => false,
                ),
                'logi_name'=>
                array(
                    'type'=>'varchar(32)',
                    'label'=>'快递公司',
                     'in_list' => true,
                  'default_in_list' => true,
                  'width' => '80',
                ),
                'deliverycomp_time' =>
                array (
                  'type' => 'time',
                  'label' => '过数时间',
                  'comment' => '过数时间',
                  'editable' => false,
                  'in_list' => true,
                  'width' => '120',
                ),
                'delivery_time' =>
                array (
                  'type' => 'time',
                  'label' => '发货时间',
                  'comment' => '发货时间',
                  'editable' => false,
                  'in_list' => true,
                  'width' => '120',
                ),
                 'branch' =>
                array(
                    'type' => 'varchar(50)',
                    'required' => true,
                    'label' => '仓库',
                    'is_title' => true,
                    'width' => 135,
                    'searchtype' => 'has',
                    'editable' => false,
                    'filtertype' => 'normal',
                    'filterdefault' => true,
                    'in_list' => true,
                    'default_in_list' => true,
                  'width' => '60',
                ),
                'logi_no' =>
                array (
                  'type' => 'varchar(32)',
                  'required' => true,
                  'label' => '快递单号',
                  'editable' => false,
                  'width' =>140,
                  'filtertype' => 'yes',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '80',
                ),
                'ship_area' =>
                array (
                  'type' => 'varchar(100)',
                  'required' => true,
                  'label' => '收货地区',
                  'comment' => '收货地区',
                  'editable' => false,
                  'width' =>140,
                  'searchtype' => 'has',
                  'filtertype' => 'yes',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '120',
                ),
                'bn' =>
                array (
                  'type' => 'varchar(100)',
                  'label' => '料号',
                  'comment' => '料号',
                  'editable' => false,
                  'width' =>140,
                  'searchtype' => 'has',
                  'filtertype' => 'yes',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '60',
                ),   
                'product_name' =>
                array (
                  'type' => 'varchar(100)',
                  'label' => '品名',
                  'comment' => '品名',
                  'editable' => false,
                  'width' =>140,
                  'searchtype' => 'has',
                  'filtertype' => 'yes',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '60',
                ),
                'unit' =>
                array (
                  'type' => 'varchar(100)',
                  'label' => '单位',
                  'comment' => '单位',
                  'editable' => false,
                  'width' =>140,
                  'searchtype' => 'has',
                  'filtertype' => 'yes',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '60',
                ),
                'net_weight' =>
                array (
                  'type' => 'number',
                  'label' => '单重（KG）',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                  'width' => '80',
                ),
                'order_weight' =>
                array (
                  'type' => 'number',
                  'label' => '总重（KG）',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                  'width' => '80',
                ),
                'number' =>
                array (
                  'type' => 'number',
                  'label' => '数量',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                  'width' => '80',
                ),               
                'flatFeePrice' =>
                array (
                  'type' => 'money',
                  'label' => '应付快递费',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                  'width' => '80',
                ),
                'lmfee' =>
                array (
                  'type' => 'money',
                  'label' => '应收快递费',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                  'width' => '80',
                ), 
                'otherfee' =>
                array (
                  'type' => 'money',
                  'label' => '差额',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                  'width' => '80',
                ),
            ),
            'idColumn' => 'name',
            'in_list' => array (
                0 => 'name',
                1 => 'jstype',
                2 => 'logi_name',
                3 => 'deliverycomp_time',
                4 => 'delivery_time',
                5 => 'branch',
                6 => 'order_bn',
                7 => 'logi_no',
                8 => 'ship_area',
                9 => 'bn',
                10 => 'product_name',
                11 => 'number',
                12 => 'unit',
                13 => 'net_weight',
                14 => 'flatFeePrice',
                15 => 'lmfee',
                16 => 'otherfee',
                17 =>'AXCustomer',
                18 =>'customername',
                19 => 'order_weight',
            ),
            'default_in_list' => array (
                0 => 'name',
                1 => 'jstype',
                2 => 'logi_name',
                3 => 'deliverycomp_time',
                4 => 'delivery_time',
                5 => 'branch',
                6 => 'order_bn',
                7 => 'logi_no',
                8 => 'ship_area',
                9 => 'bn',
                10 => 'product_name',
                11 => 'number',
                12 => 'unit',
                13 => 'net_weight',
                14 => 'flatFeePrice',
                15 => 'lmfee',
                16 => 'otherfee',
                17 =>'AXCustomer',
                18 =>'customername',
                19 => 'order_weight',
            ),
        );
        return $schema;
    }

    /**
     * 获得日志类型(non-PHPdoc)
     * @see dbeav_model::getLogType()
     */
    public function getLogType($logParams) {
        $type = $logParams['type'];
        $logType = 'none';
        if ($type == 'export') {
            $logType = $this->exportLogType($logParams);
        }
        elseif ($type == 'import') {
            $logType = $this->importLogType($logParams);
        }
        return $logType;
    }
    /**
     * 导出日志类型
     * @param Array $logParams 日志参数
     */
    public function exportLogType($logParams) {
        $params = $logParams['params'];
        $type = 'report';
        if ($logParams['app'] == 'omeanalysts' && $logParams['ctl'] == 'ome_delivery') {
            $type .= '_purchaseReport_expressAnalysis';
        }
        $type .= '_export';
        return $type;
    }
    /**
     * 导入操作日志类型
     * @param Array $logParams 日志参数
     */
    public function importLogType($logParams) {
        $params = $logParams['params'];
        $type = 'report';
        if ($logParams['app'] == 'omeanalysts' && $logParams['ctl'] == 'ome_delivery') {
            $type .= '_purchaseReport_expressAnalysis';
        }
        $type .= '_import';
        return $type;
    }

    function io_title( $filter, $ioType='csv' ){

        switch( $filter ){
            case 'delivery':
                $this->oSchema['csv'][$filter] = array(
                    '*:店铺' => 'name',
                    '*:客户编号' => 'AXCustomer',
                    '*:客户名称' => 'customername',
                    '*:结算方式' => 'jstype',
                    '*:快递公司' => 'logi_name',
                    '*:过数时间' => 'deliverycomp_time',
                    '*:发货时间' => 'delivery_time',
                    '*:仓库' => 'branch',
                    '*:AX订单号' => 'order_bn',
                    '*:快递单号' => 'logi_no',
                    '*:收货地区' => 'ship_area',
                    '*:料号' => 'bn',
                    '*:品名' => 'product_name',
                    '*:数量' => 'number',
                    '*:单位' => 'unit',
                    '*:单重（KG)' => 'order_weight',
                    '*:总重（KG)' => 'net_weight',
                    '*:应付快递费' => 'flatFeePrice',
                    '*:应收快递费' => 'lmfee',
                    '*:差额' => 'otherfee',
                );
                break;
        }
        $this->ioTitle[$ioType][$filter] = array_keys( $this->oSchema[$ioType][$filter] );
        return $this->ioTitle[$ioType][$filter];
    }

    //根据查询条件获取导出数据
    public function getExportDataByCustom($fields, $filter, $has_detail, $curr_sheet, $start, $end){
          //根据选择的字段定义导出的第一行标题
          if($curr_sheet == 1){

              $title = array();
              foreach($this->io_title('delivery') as $k => $v ){
                  $title[] = mb_convert_encoding($v, 'GBK', 'UTF-8');
              }

              $data['content']['main'][0] = '"'.implode('","',$title).'"';
          }

          $where = $this->_filter($filter);

      
            $sql = "SELECT f.`name`,f.AXCustomer,f.customername,case when f.jstype ='0' then '代收代付' when f.jstype='1' then '理文支付' when f.jstype='2' then '客户支付' else '' end  jstype,e.logi_name,FROM_UNIXTIME(a.deliverycomp_time) deliverycomp_time,FROM_UNIXTIME(e.delivery_time) as delivery_time,sob.`name` as branch,d.axorderno order_bn,db.logi_no,e.ship_area,items.bn,items.product_name,items.number,ext.unit,e.net_weight/1000 net_weight,e.net_weight/1000 order_weight,
            case when f.jstype ='0' then e.delivery_cost_actual when f.jstype='1' then e.delivery_cost_actual when f.jstype='2' then 0 else e.delivery_cost_actual end  flatFeePrice,
            case when f.jstype ='0' then e.lmfee when f.jstype='1' then 0 when f.jstype='2' then 0 else e.lmfee end lmfee,
            ((case when f.jstype ='0' then e.lmfee when f.jstype='1' then 0 when f.jstype='2' then 0 else e.lmfee end) -(case when f.jstype ='0' then e.delivery_cost_actual when f.jstype='1' then e.delivery_cost_actual when f.jstype='2' then 0 else e.delivery_cost_actual end)) otherfee
                         from  sdb_wms_deliverycomp a 
                         inner join sdb_wms_deliverycomp_line b on a.id = b.deliverycomp_id
                         inner join sdb_wms_deliverynote_line d on b.deliverynote_id = d.deliverynote_id 
                         inner join sdb_wms_delivery e on d.delivery_bn = e.delivery_bn
                         inner join sdb_wms_delivery_bill db on e.delivery_id = db.delivery_id 
                         inner join sdb_wms_delivery_items items on e.delivery_id=items.delivery_id
                         inner join sdb_ome_shop f on e.shop_id = f.shop_id
                         inner JOIN sdb_ome_delivery od on ( e.outer_delivery_bn = od.delivery_bn )
                         inner JOIN sdb_ome_delivery_order odo on ( od.delivery_id = odo.delivery_id )
                         inner JOIN sdb_ome_orders os on (odo.order_id = os.order_id)
                         inner JOIN sdb_ome_branch sob on (sob.branch_id = e.branch_id)
                         inner JOIN sdb_material_basic_material_ext ext on items.product_id=ext.bm_id 
                         where  ".$where." ";
            $omedelivery = $this->db->selectLimit($sql,$end,$start);
            foreach ($omedelivery as $k => $aFilter) {
                $exptmp_data = array();
                foreach ($aFilter as $col => $val) {
                    $aFilter[$col] = mb_convert_encoding($aFilter[$col], 'GBK', 'UTF-8');
                    $exptmp_data[] = $aFilter[$col];
                }

                $data['content']['main'][] = implode(',', $exptmp_data);
            }
            return $data;
        
    }
}
